package com.zwt.utils;

import com.zwt.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtil {

    public static void main(String[] args) throws IOException {

        //test
        new HtmlParseUtil().parseJD("java").forEach(System.out::println);
    }


    public List<Content> parseJD(String keywords) throws IOException {
        //获得请求  https://search.jd.com/Search?keyword=java
        //联网 ajax需要模拟浏览器才可以获取
        String url = "https://search.jd.com/Search?keyword=" + keywords;
        //解析网页,返回的就是Document对象
        Document document = Jsoup.parse(new URL(url), 30000);
        //所有JS中的方法这里都可以使用
        Element element = document.getElementById("J_goodsList");
//        System.out.println(element.html());


        ArrayList<Content> goodsList = new ArrayList<>();
        //找到所有的列元素
        Elements elements = element.getElementsByTag("li");
        //这里的el就是每一个列标签
        for (Element el : elements) {

            //关于这种图片特别多的网站，都是后面加载的

            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

//            System.out.println("爬取京东的数据结果:");
//            System.out.println("==========================================");
//            System.out.println(img);
//            System.out.println(price);
//            System.out.println(title);
            Content content = new Content();
            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);
            goodsList.add(content);
        }


        return goodsList;

    }

}
